package com.zide.system.controller;

import cn.hutool.core.util.ObjectUtil;
import com.zide.common.annotation.Log;
import com.zide.common.constant.CacheConstants;
import com.zide.common.core.domain.CommonResult;
import com.zide.common.core.domain.PageResult;
import com.zide.common.core.domain.entity.SysUser;
import com.zide.common.core.redis.RedisCache;
import com.zide.common.enums.BusinessType;
import com.zide.common.utils.SecurityUtils;
import com.zide.system.domain.dept.vo.search.SysDeptSearchVO;
import com.zide.framework.web.domain.vo.result.SysRoleResultVO;
import com.zide.framework.web.domain.vo.save.SysRoleSaveVO;
import com.zide.system.domain.user.vo.result.SystemUserResultVO;
import com.zide.framework.web.mapper.SysUserSearchVO;
import com.zide.framework.web.service.impl.SysPermissionService;
import com.zide.framework.web.domain.po.SysUserRole;
import com.zide.framework.web.domain.vo.search.SysRoleSearchVO;
import com.zide.system.service.ISysDeptService;
import com.zide.framework.web.service.ISysRoleService;
import com.zide.system.service.ISysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static com.zide.common.core.domain.CommonResult.*;

/**
 * 角色信息
 *
 * @author zide
 */
@Tag(name = "角色管理")
@RestController
@RequestMapping("/system/role")
public class SysRoleController {
    @Resource
    private ISysRoleService roleService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private RedisCache redisCache;
    @Resource
    private ISysUserService userService;

    @Resource
    private ISysDeptService deptService;

    @Operation(summary = "角色列表")
    @GetMapping("/list")
    public CommonResult list(SysRoleSearchVO searchVO) {
        PageResult<SysRoleResultVO> list = roleService.selectRolePage(searchVO);
        return success(list);
    }

    @Operation(summary = "根据角色编号获取详细信息")
    @GetMapping(value = "/{roleId}")
    public CommonResult getInfo(@PathVariable Long roleId) {
        roleService.checkRoleDataScope(roleId);
        return success(roleService.selectRoleById(roleId));
    }

    @Operation(summary = "新增角色")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public CommonResult add(@Validated @RequestBody SysRoleSaveVO saveVO) {
        if (!roleService.checkRoleNameUnique(saveVO)) {
            return error("新增角色'" + saveVO.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(saveVO)) {
            return error("新增角色'" + saveVO.getRoleName() + "'失败，角色权限已存在");
        }
        return getResult(roleService.insertRole(saveVO));

    }

    @Operation(summary = "修改角色")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public CommonResult edit(@Validated @RequestBody SysRoleSaveVO saveVO) {
        roleService.checkRoleAllowed(saveVO);
        roleService.checkRoleDataScope(saveVO.getRoleId());
        if (!roleService.checkRoleNameUnique(saveVO)) {
            return error("修改角色'" + saveVO.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(saveVO)) {
            return error("修改角色'" + saveVO.getRoleName() + "'失败，角色权限已存在");
        }
        if (roleService.updateRole(saveVO) > 0) {
            // 更新缓存用户权限
            SysUser user = SecurityUtils.getLoginUser().getUser();
            if (ObjectUtil.isNotNull(user) && !user.isAdmin()) {
                user.setPermissions(permissionService.getMenuPermission(user));
                user = userService.selectUserByUserName(user.getUsername());
                redisCache.setCacheObject(CacheConstants.PRE_SYSUSER + user.getUserId(),user);
            }
            return success();
        }
        return error("修改角色'" + saveVO.getRoleName() + "'失败，请联系管理员");
    }

    @Operation(summary = "修改保存数据权限")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public CommonResult dataScope(@RequestBody SysRoleSaveVO saveVO) {
        roleService.checkRoleAllowed(saveVO);
        roleService.checkRoleDataScope(saveVO.getRoleId());
        return getResult(roleService.authDataScope(saveVO));
    }

    @Operation(summary = "状态修改")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public CommonResult changeStatus(@RequestBody SysRoleSaveVO saveVO) {
        roleService.checkRoleAllowed(saveVO);
        roleService.checkRoleDataScope(saveVO.getRoleId());
        return getResult(roleService.updateRoleStatus(saveVO));
    }

    @Operation(summary = "删除角色")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public CommonResult remove(@PathVariable Long[] roleIds) {
        return getResult(roleService.deleteRoleByIds(roleIds));
    }

    @Operation(summary = "获取角色选择框列表")
    @GetMapping("/optionselect")
    public CommonResult optionselect() {
        return success(roleService.selectRoleAll());
    }

    @Operation(summary = "查询已分配用户角色列表")
    @GetMapping("/authUser/allocatedList")
    public CommonResult allocatedList(SysUserSearchVO searchVO) {

        PageResult<SystemUserResultVO> result = userService.selectAllocatedList(searchVO);
        return success(result);
    }

    @Operation(summary = "查询未分配用户角色列表")
    @GetMapping("/authUser/unallocatedList")
    public CommonResult unallocatedList(SysUserSearchVO searchVO) {
        PageResult<SystemUserResultVO> result = userService.selectUnallocatedList(searchVO);
        return success(result);
    }

    @Operation(summary = "取消授权用户")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public CommonResult cancelAuthUser(@RequestBody SysUserRole userRole) {
        return getResult(roleService.deleteAuthUser(userRole));
    }

    @Operation(summary = "批量取消授权用户")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public CommonResult cancelAuthUserAll(Long roleId, Long[] userIds) {
        return getResult(roleService.deleteAuthUsers(roleId, userIds));
    }

    @Operation(summary = "批量选择用户授权")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public CommonResult selectAuthUserAll(Long roleId, Long[] userIds) {
        roleService.checkRoleDataScope(roleId);
        return getResult(roleService.insertAuthUsers(roleId, userIds));
    }

    @Operation(summary = "获取对应角色部门树列表")
    @GetMapping(value = "/deptTree/{roleId}")
    public CommonResult deptTree(@PathVariable("roleId") Long roleId) {
        CommonResult ajax = CommonResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.selectDeptTreeList(new SysDeptSearchVO()));
        return ajax;
    }
}
